/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.worker.receiver;

import java.security.cert.X509Certificate;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.ourgrid.common.interfaces.AccountingAggregator;
import org.ourgrid.common.interfaces.WorkerSpecListener;
import org.ourgrid.common.interfaces.management.RemoteWorkerManagement;
import org.ourgrid.common.interfaces.management.WorkerManagement;
import org.ourgrid.common.interfaces.management.WorkerManagementClient;
import org.ourgrid.common.interfaces.to.WorkerStatus;
import org.ourgrid.reqtrace.Req;
import org.ourgrid.worker.WorkerConfiguration;
import org.ourgrid.worker.WorkerConstants;
import org.ourgrid.worker.controller.ExecutionController;
import org.ourgrid.worker.controller.WorkerController;
import org.ourgrid.worker.dao.WorkAccountingDAO;
import org.ourgrid.worker.dao.WorkerSpecListenerDAO;
import org.ourgrid.worker.dao.WorkerStatusDAO;
import org.ourgrid.worker.messages.ControlMessages;
import org.ourgrid.worker.messages.WorkerManagementControllerMessages;

import br.edu.ufcg.lsd.commune.api.FailureNotification;
import br.edu.ufcg.lsd.commune.api.InvokeOnDeploy;
import br.edu.ufcg.lsd.commune.api.MonitoredBy;
import br.edu.ufcg.lsd.commune.api.RecoveryNotification;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;

/**
 * WorkerManagementReceiver, called by the management peer.
 *  Its callback is WorkerManagementClient.
 * @see org.ourgrid.common.interfaces.management.WorkerManagement
 */
@Req("REQ004")
public class WorkerManagementReceiver implements WorkerManagement {
	
	private static final long serialVersionUID = 1L;

	private ServiceManager serviceManager;

	@Req("REQ090")
	@InvokeOnDeploy
	public void init(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}
	
	/**
	 * @return the serviceManager
	 */
	protected ServiceManager getServiceManager() {
		return serviceManager;
	}
	
	@Req({"REQ006", "REQ090"})
	public void setPeer(@MonitoredBy(WorkerConstants.LOCAL_WORKER_MANAGEMENT_CLIENT_MONITOR) WorkerManagementClient workerManagementClient, 
			@MonitoredBy(WorkerConstants.LOCAL_WORKER_MANAGEMENT) AccountingAggregator accounting,
			@MonitoredBy(WorkerConstants.LOCAL_WORKER_MANAGEMENT) WorkerSpecListener workerSpecListener) {
		
		DeploymentID peerID = getServiceManager().getStubDeploymentID(workerManagementClient);
		String senderPublicKey = getServiceManager().getSenderPublicKey();
		
		if (!senderPublicKey.equals(getPeerPubKey())) {
			getServiceManager().getLog().warn(WorkerManagementControllerMessages.getUnknownPeerSetPeerMessage(peerID, senderPublicKey));
			return;
		}
		
		WorkerStatus workerStatus = getWorkerStatusDAO().getStatus(); 
		
		
		if (getWorkerStatusDAO().isMasterPeerUp() && getWorkerStatusDAO().getMasterPeerDID().equals(peerID)) {
			getServiceManager().getLog().warn(WorkerManagementControllerMessages.getMasterPeerThatDidNotFailTryToSetPeerAgain(peerID));
			workerManagementClient.statusChanged(workerStatus);
			return;
		}
		
		getServiceManager().getLog().info(WorkerManagementControllerMessages.getPeerSetPeerMessage(peerID));
		getWorkerStatusDAO().setMasterPeer(workerManagementClient, peerID);
		
		getWorkAccountingDAO().setAcountingAggregator(accounting);

		Future<?> future = getServiceManager().scheduleActionWithFixedDelay(WorkerConstants.REPORT_WORK_ACCOUNTING_ACTION_NAME, 
				WorkerConstants.REPORT_WORK_ACCOUNTING_TIME, TimeUnit.SECONDS);
		getWorkAccountingDAO().setReportAccountingActionFuture(future);
		
		WorkerController.getInstance().interruptWorking(getServiceManager(), true);
		
		String propIdlenessDetector = 
			(String) getServiceManager().getContainerContext().getProperty(WorkerConfiguration.PROP_IDLENESS_DETECTOR);
		
		boolean isIdlenessDetectorOn = (propIdlenessDetector == null) ? 
			false : !propIdlenessDetector.equals(WorkerConfiguration.DEF_PROP_IDLENESS_DETECTOR);
		
		WorkerStatus newStatus = isIdlenessDetectorOn ? WorkerStatus.OWNER : WorkerStatus.IDLE;
		
		if (!workerStatus.equals(newStatus)) {
			getWorkerStatusDAO().setStatus(newStatus);
//			getServiceManager().getLog().debug(ControlMessages.getWorkerStatusChangedMessage(workerStatus, newStatus));
		}
		
		workerManagementClient.statusChanged(newStatus);
		getServiceManager().getDAO(WorkerSpecListenerDAO.class).addWorkerSpecListener(workerSpecListener);
		
		String propCollector = 
			(String) getServiceManager().getContainerContext().getProperty(WorkerConfiguration.PROP_COLLECTOR);
		
		boolean isCollectorPropOn = (propCollector == null) ? false: 
			!propCollector.equals(WorkerConfiguration.DEF_PROP_COLLECTOR);
		
		if	(isCollectorPropOn) { 
			getServiceManager().scheduleActionWithFixedDelay(
					WorkerConstants.REPORT_WORKER_SPEC_ACTION_NAME, 
					getServiceManager().getContainerContext().parseLongProperty(
							WorkerConfiguration.PROP_WORKER_SPEC_UPDATE_TIME) * 1000, TimeUnit.MILLISECONDS);
		}
		
	}

	@Req({"REQ006", "REQ092"})
	public void workForBroker(DeploymentID brokerID) {
		String senderPublicKey = getServiceManager().getSenderPublicKey();
		
		if (!senderPublicKey.equals(getPeerPubKey())) {
			getServiceManager().getLog().warn(WorkerManagementControllerMessages.getUnknownPeerTryingToCommandWorkerToWorkForMyGridMessage(senderPublicKey));
			return;
		}
		
		WorkerManagementClient masterPeer = getWorkerStatusDAO().getMasterPeer();
		if (masterPeer == null) {
			getServiceManager().getLog().debug(WorkerManagementControllerMessages.getMasterPeerTryingToCommandWorkerBeforeSettingAsManagerMessage());
			return;
		}
		
		WorkerStatus actualStatus = getWorkerStatusDAO().getStatus();
		if (actualStatus.equals(WorkerStatus.OWNER)) {
			getServiceManager().getLog().debug(WorkerManagementControllerMessages.getMasterPeerCommandedOwnerWorkerToWorkForMyGridMessage());
			return;
		}
		
		getServiceManager().getLog().info(WorkerManagementControllerMessages.getMasterPeerCommandedWorkerToWorkForMyGridMessage(brokerID));

		if (getWorkerStatusDAO().isAllocated()) {
			preemptWorker();
		}

		if (!actualStatus.equals(WorkerStatus.ALLOCATED_FOR_BROKER)) {
			getServiceManager().getLog().debug(ControlMessages.getWorkerStatusChangedMessage(
					actualStatus, WorkerStatus.ALLOCATED_FOR_BROKER));
			getWorkerStatusDAO().setStatus(WorkerStatus.ALLOCATED_FOR_BROKER);
		}

		getWorkerStatusDAO().setConsumerPublicKey(brokerID.getPublicKey());
		
		ExecutionController.getInstance().beginAllocation(getServiceManager());
		
	}
	
	private void preemptWorker() {
		WorkerController.getInstance().interruptWorking(getServiceManager(), true);
	}

	public void workForPeer(String peerPubKey, List<String> usersDN,
			List<X509Certificate> caCertificates) {
		
		RemoteWorkerManagement remWorkerManag = prepareToWorkForPeer(peerPubKey);
		if (remWorkerManag == null) {
			return;
		}
		
		getWorkerStatusDAO().setUsersDN(usersDN);
		getWorkerStatusDAO().setCaCertificates(caCertificates);
		getWorkerStatusDAO().getMasterPeer().statusChangedAllocatedForPeer(remWorkerManag);
	}
	
	@Req("REQ006")
	public void workForPeer(String peerPubKey) {
		
		RemoteWorkerManagement remWorkerManag = prepareToWorkForPeer(peerPubKey);
		if (remWorkerManag == null) {
			return;
		}
		
		getWorkerStatusDAO().getMasterPeer().statusChangedAllocatedForPeer(remWorkerManag);
	}

	private RemoteWorkerManagement prepareToWorkForPeer(String peerPubKey) {
		String senderPubKey = getServiceManager().getSenderPublicKey();
		
		if (!senderPubKey.equals(getPeerPubKey())) {
			getServiceManager().getLog().warn(WorkerManagementControllerMessages.getUnknownPeerSendsWorkForPeerMessage(senderPubKey));
			return null;
		}
		
		WorkerManagementClient masterPeer = getWorkerStatusDAO().getMasterPeer();
		if (masterPeer == null) {
			getServiceManager().getLog().debug(WorkerManagementControllerMessages.getUnsetMasterPeerSendsWorkForPeerMessage());
			return null;
		}
		
		if (getWorkerStatusDAO().getStatus().equals(WorkerStatus.OWNER)) {
			getServiceManager().getLog().debug(WorkerManagementControllerMessages.getWorkForPeerOnOwnerWorkerMessage());
			return null;
		}
		
		getServiceManager().getLog().info(WorkerManagementControllerMessages.getSuccessfulWorkForPeerMessage(peerPubKey));
		if (getWorkerStatusDAO().getStatus().equals(WorkerStatus.ALLOCATED_FOR_BROKER)) {
			getServiceManager().getLog().warn(WorkerManagementControllerMessages.getWorkForPeerOnAllocatedForMyGridWorkerMessage());
		}
		
		if (getWorkerStatusDAO().isAllocated()) {
			preemptWorker();
		}
		
		if (!getWorkerStatusDAO().getStatus().equals(WorkerStatus.ALLOCATED_FOR_PEER)) {
			getServiceManager().getLog().debug(ControlMessages.getWorkerStatusChangedMessage(
					getWorkerStatusDAO().getStatus(), WorkerStatus.ALLOCATED_FOR_PEER));
			getWorkerStatusDAO().setStatus(WorkerStatus.ALLOCATED_FOR_PEER);
		}
		
		getWorkerStatusDAO().setRemotePeerPublicKey(peerPubKey);

		RemoteWorkerManagement remWorkerManag = new RemoteWorkerManagementReceiver();
		getServiceManager().deploy(WorkerConstants.REMOTE_WORKER_MANAGEMENT, remWorkerManag);
		return remWorkerManag;
	}
	
	@Req("REQ091")
	public void stopWorking() {
		
		String senderPubKey = getServiceManager().getSenderPublicKey();
		
		if(!senderPubKey.equals(getPeerPubKey())) {
			getServiceManager().getLog().warn(WorkerManagementControllerMessages.getStopWorkingByUnknownPeerMessage(senderPubKey));
			return;
		}
		
		WorkerManagementClient masterPeer = getWorkerStatusDAO().getMasterPeer();
		if(masterPeer == null) {
			getServiceManager().getLog().warn(WorkerManagementControllerMessages.getMasterPeerTryingToCommandWorkerBeforeSettingAsManagerMessage());
			return;
		}
		
		if(!getWorkerStatusDAO().isAllocated()) {
			getServiceManager().getLog().warn(WorkerManagementControllerMessages.getStopWorkingOnNotWorkingWorkerMessage());
			return;
		}
		
		WorkerController.getInstance().interruptWorking(getServiceManager(), true);
		
		getServiceManager().getLog().info(WorkerManagementControllerMessages.getSuccessfulStopWorkingMessage());

		WorkerStatus oldStatus = getWorkerStatusDAO().getStatus();
		WorkerStatus newStatus = WorkerStatus.IDLE;
		getWorkerStatusDAO().setStatus(newStatus);
		getServiceManager().getLog().debug(ControlMessages.getWorkerStatusChangedMessage(oldStatus, newStatus));
		
		masterPeer.statusChanged(newStatus);
	}
	
	private WorkerStatusDAO getWorkerStatusDAO() {
		return getServiceManager().getDAO(WorkerStatusDAO.class);
	}
	
	private WorkAccountingDAO getWorkAccountingDAO() {
		return getServiceManager().getDAO(WorkAccountingDAO.class);
	}
	
	private String getPeerPubKey() {
		return getServiceManager().getContainerContext().getProperty(WorkerConfiguration.PROP_PEER_PUBLIC_KEY);
	}
	
	@RecoveryNotification
	public void accAggregatorIsUp(AccountingAggregator accounting) {}
	
	@FailureNotification
	public void accAggregatorIsDown(AccountingAggregator accounting) {}

	@RecoveryNotification
	public void listenerIsUp(WorkerSpecListener client) {}
	
	@FailureNotification
	public void listenerIsDown(WorkerSpecListener client) {}
}